package com.pshcp.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSONObject;
import com.external.dahantc.DahantcService;
import com.external.hospital.ap.UserApManager;
import com.framework.base.ResultBuilder;
import com.framework.base.ResultDTO;
import com.framework.common.config.CustomConf;
import com.framework.exception.BizException;
import com.framework.logaop.Log;
import com.framework.logaop.LogSourceEnum;
import com.framework.logaop.LogTypeEnum;
import com.framework.thread.ReqComTool;
import com.framework.tool.CommonTool;
import com.framework.util.DateUtil;
import com.framework.util.JwtUtil;
import com.framework.util.SecurityUtil;
import com.pshcp.ao.common.ClosePatientAccountAO;
import com.pshcp.ao.common.DownloadAppAO;
import com.pshcp.ao.common.ForgotPasswordAO;
import com.pshcp.ao.common.LoginAO;
import com.pshcp.ao.common.PatientWechat2PhoneLoginAO;
import com.pshcp.ao.common.PatientWechatSessionAO;
import com.pshcp.ao.common.RegisterAO;
import com.pshcp.ao.common.SmsCaptchaAO;
import com.pshcp.ao.common.UpdatePwdAO;
import com.pshcp.ao.common.VerifySmsCaptchaAO;
import com.pshcp.ao.common.VersionCheckAO;
import com.pshcp.ao.common.WechatPatientLoginAO;
import com.pshcp.common.config.WxMaConfiguration;
import com.pshcp.domain.dto.AppVersionDTO;
import com.pshcp.domain.model.AppVersion;
import com.pshcp.domain.model.Doctor;
import com.pshcp.domain.model.PatientUser;
import com.pshcp.domain.model.Session;
import com.pshcp.domain.model.SmsCaptcha;
import com.pshcp.domain.vo.AppVersionVO;
import com.pshcp.service.AppVersionService;
import com.pshcp.service.DoctorService;
import com.pshcp.service.PatientUserService;
import com.pshcp.service.SessionService;
import com.pshcp.service.SmsCaptchaService;
import com.pshcp.tool.AppCommonTool;
import com.pshcp.tool.SessionTool;
import com.pshcp.vo.common.DoctorLoginVO;
import com.pshcp.vo.common.LoginVO;
import com.pshcp.vo.common.PatientWechatSessionVO;
import com.pshcp.vo.common.UserProfileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description: 通用接口
 * @Author: xiaoche
 * @Date: 2022/11/2 22:22
 */
@Api(tags = {"通用接口"})
@Slf4j
@RestController
@RequestMapping("/api/common")
public class CommonAPI {

    @Autowired
    private CustomConf customConf;
    @Autowired
    private SmsCaptchaService smsCaptchaService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private PatientUserService patientUserService;

    @Autowired
    private AppVersionService appVersionService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SessionService sessionService;

    @Autowired
    private DahantcService dahantcService;

    @Autowired
    private UserApManager userApManager;

    @Value("${custom.download.app.qr.patient}")
    private String downloadAppQrPatient;

    @Value("${custom.download.app.qr.doctor}")
    private String downloadAppQrDoctor;


    @ApiOperation("获取短信验证码")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "获取短信验证码")
    @PostMapping("sendSmsCaptcha")
    public ResultDTO<Long> sendSmsCaptcha(@RequestBody SmsCaptchaAO smsCaptchaAO) throws BizException {
        AppCommonTool.checkSendSmsCode(smsCaptchaAO);
        if (smsCaptchaAO.getPurpose() == 0 || smsCaptchaAO.getPurpose() == 2 || smsCaptchaAO.getPurpose() == 3) {
            if (smsCaptchaAO.getTerminal() == 0) {
                Doctor doctorByPhone = doctorService.getDoctorByPhone(smsCaptchaAO.getPhone());
                CommonTool.checkObj(doctorByPhone, "10010005");
            }
            if (smsCaptchaAO.getTerminal() == 1) {
                PatientUser patientUserByPhone = patientUserService.getPatientUserByPhone(smsCaptchaAO.getPhone());
                CommonTool.checkObj(patientUserByPhone, "10010005");
            }
        }
        SmsCaptcha latestUnUseSmsCaptcha = smsCaptchaService.getLatestUnUseSmsCaptcha(smsCaptchaAO.getTerminal(), smsCaptchaAO.getPurpose(), smsCaptchaAO.getPhone());
        if (latestUnUseSmsCaptcha != null) {
            if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(latestUnUseSmsCaptcha.getCreatedTime(), customConf.getSmsCaptchaTime()).getTime() < 0) {
                return ResultBuilder.failure("10010006");
            }
        }
        SmsCaptcha smsCaptcha = AppCommonTool.buildSendSmsCode(smsCaptchaAO);
        smsCaptchaService.insert(smsCaptcha);
        dahantcService.sendSms(smsCaptcha.getType(), smsCaptcha.getId().toString(), smsCaptcha.getPhone(), smsCaptcha.getCode());
        return ResultBuilder.success(smsCaptcha.getId());
    }

    @ApiOperation("验证短信验证码")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "验证短信验证码")
    @PostMapping("verifySmsCaptcha")
    public ResultDTO<Long> verifySmsCaptcha(@RequestBody VerifySmsCaptchaAO verifySmsCaptchaAO) throws BizException {
        AppCommonTool.checkVerifySmsCaptcha(verifySmsCaptchaAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(verifySmsCaptchaAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 1 || !verifySmsCaptchaAO.getSmsCode().equals(smsCaptcha.getCode())) {
            return ResultBuilder.failure("10010009");
        }
        smsCaptcha.setBizStatus(1);
        smsCaptchaService.update(smsCaptcha);
        return ResultBuilder.success(null);
    }

    @ApiOperation("APP医生端忘记密码")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP医生端忘记密码")
    @PostMapping("doctorForgotPassword")
    public ResultDTO<String> doctorForgotPassword(@RequestBody ForgotPasswordAO forgotPasswordAO) throws Exception {
        AppCommonTool.checkForgotPassword(forgotPasswordAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(forgotPasswordAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0) {
            return ResultBuilder.failure("10010031");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010032");
        }
        Doctor doctorByPhone = doctorService.getDoctorByPhone(forgotPasswordAO.getPhone());
        CommonTool.checkObj(doctorByPhone, "90000007");
        Doctor doctor = AppCommonTool.buildDoctorForgotPassword(doctorByPhone, forgotPasswordAO);
        doctorService.update(doctor);
        return ResultBuilder.success(null);
    }

    @ApiOperation("APP医生端登录")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP医生端登录")
    @PostMapping("doctorLogin")
    public ResultDTO<DoctorLoginVO> doctorLogin(@RequestBody LoginAO loginAO) throws Exception {
        AppCommonTool.checkLogin(loginAO);
        Doctor doctorByPhone = doctorService.getDoctorByPhone(loginAO.getPhone());
        CommonTool.checkObj(doctorByPhone, "10010024");
        if (loginAO.getType() == 0) {
            if (!doctorByPhone.getPassword().equals(SecurityUtil.MD5(loginAO.getPassword()))) {
                return ResultBuilder.failure("10010024");
            }
        }
        if (loginAO.getType() == 1) {
            SmsCaptcha smsCaptcha = smsCaptchaService.findById(loginAO.getSmsPkId());
            if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0 || !loginAO.getSmsCode().equals(smsCaptcha.getCode())) {
                return ResultBuilder.failure("10010025");
            }
            if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
                return ResultBuilder.failure("10010017");
            }
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 0, doctorByPhone.getId());
        sessionService.insert(session);
        DoctorLoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId(), doctorByPhone.getName());
        return ResultBuilder.success(loginVO);
    }

    @ApiOperation("APP医生端修改密码")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP医生端修改密码")
    @PostMapping("doctorUpdatePwd")
    public ResultDTO<Long> doctorUpdatePwd(@RequestBody UpdatePwdAO updatePwdAO) throws Exception {
        AppCommonTool.checkUpdatePassword(updatePwdAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(updatePwdAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0 || !updatePwdAO.getSmsCode().equals(smsCaptcha.getCode())) {
            return ResultBuilder.failure("10010031");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010032");
        }
        Doctor doctorByPhone = doctorService.findById(ReqComTool.getUserId());
        Doctor doctor = AppCommonTool.buildDoctorUpdatePassword(doctorByPhone, updatePwdAO.getPassword());
        doctorService.update(doctor);
        return ResultBuilder.success(null);
    }

    @ApiOperation("APP患者端注册")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP医生端注册")
    @PostMapping("patientRegister")
    public ResultDTO<String> patientRegister(@RequestBody RegisterAO registerAO) throws Exception {
        AppCommonTool.checkRegister(registerAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(registerAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0) {
            return ResultBuilder.failure("10010016");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010017");
        }
        PatientUser patientUserByPhone = patientUserService.getPatientUserByPhone(registerAO.getPhone());
        CommonTool.checkExistObj(patientUserByPhone, "10010018");
        PatientUser patientUser = AppCommonTool.buildPatientUserRegister(registerAO);
        patientUserService.insert(patientUser);
        //sync to platform
        userApManager.savePatient(patientUser);
        return ResultBuilder.success(null);
    }

    @ApiOperation("APP患者端忘记密码")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP患者端忘记密码")
    @PostMapping("patientForgotPassword")
    public ResultDTO<String> patientForgotPassword(@RequestBody ForgotPasswordAO forgotPasswordAO) throws Exception {
        AppCommonTool.checkForgotPassword(forgotPasswordAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(forgotPasswordAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0) {
            return ResultBuilder.failure("10010031");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010032");
        }
        PatientUser patientUserByPhone = patientUserService.getPatientUserByPhone(forgotPasswordAO.getPhone());
        CommonTool.checkObj(patientUserByPhone, "90000007");
        PatientUser patientUser = AppCommonTool.buildPatientUserForgotPassword(patientUserByPhone, forgotPasswordAO);
        patientUserService.update(patientUser);
        return ResultBuilder.success(null);
    }

    @ApiOperation("APP患者端登录")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "APP患者端登录")
    @PostMapping("patientLogin")
    public ResultDTO<LoginVO> patientLogin(@RequestBody LoginAO loginAO) throws Exception {
        AppCommonTool.checkLogin(loginAO);
        PatientUser patientUserByPhone = patientUserService.getPatientUserByPhone(loginAO.getPhone());
        CommonTool.checkObj(patientUserByPhone, "10010026");
        if (loginAO.getType() == 0) {
            if (StringUtils.isBlank(patientUserByPhone.getPassword()) || !patientUserByPhone.getPassword().equals(SecurityUtil.MD5(loginAO.getPassword()))) {
                return ResultBuilder.failure("10010026");
            }
        }
        if (loginAO.getType() == 1) {
            SmsCaptcha smsCaptcha = smsCaptchaService.findById(loginAO.getSmsPkId());
            if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0 || !loginAO.getSmsCode().equals(smsCaptcha.getCode())) {
                return ResultBuilder.failure("10010027");
            }
            if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
                return ResultBuilder.failure("10010017");
            }
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 1, patientUserByPhone.getId());
        sessionService.insert(session);
        LoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId());
        return ResultBuilder.success(loginVO);
    }


    @ApiOperation("微信端患者获取私钥")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "微信端患者获取私钥")
    @PostMapping("getPatientWechatSession")
    public ResultDTO<PatientWechatSessionVO> getPatientWechatSession(@RequestBody PatientWechatSessionAO patientWechatSessionAO) throws Exception {
        CommonTool.checkString(patientWechatSessionAO.getCode(), "90000012");
        final WxMaService wxService = WxMaConfiguration.getMaService();
        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxService.getUserService().getSessionInfo(patientWechatSessionAO.getCode());
        CommonTool.checkObj(wxMaJscode2SessionResult, "90000013");
        PatientUser patientUser = patientUserService.getPatientUserByOpenid(wxMaJscode2SessionResult.getOpenid());
        if (patientUser == null) {
            PatientWechatSessionVO patientWechatSessionVO = AppCommonTool.buildPatientWechatSessionVO(wxMaJscode2SessionResult, null, null, null);
            return ResultBuilder.success(patientWechatSessionVO);
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 2, patientUser.getId());
        sessionService.insert(session);
        PatientWechatSessionVO patientWechatSessionVO = AppCommonTool.buildPatientWechatSessionVO(wxMaJscode2SessionResult, patientUser, session.getToken(), session.getUserId());
        return ResultBuilder.success(patientWechatSessionVO);
    }

    @ApiOperation("微信小程序患者端登录")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "微信小程序患者端登录")
    @PostMapping("patientWechatLogin")
    public ResultDTO<LoginVO> patientWechatLogin(@RequestBody WechatPatientLoginAO wechatPatientLoginAO) throws Exception {
        CommonTool.checkString(wechatPatientLoginAO.getOpenid(), "90000012");
        CommonTool.checkString(wechatPatientLoginAO.getSessionKey(), "90000012");
        CommonTool.checkString(wechatPatientLoginAO.getEncryptedData(), "90000012");
        CommonTool.checkString(wechatPatientLoginAO.getIv(), "90000012");
        CommonTool.checkString(wechatPatientLoginAO.getCheckSignature(), "90000012");
        String checkSignature = SecurityUtil.MD5(wechatPatientLoginAO.getOpenid() + "_" + (wechatPatientLoginAO.getSessionKey()));
        if (!checkSignature.equals(wechatPatientLoginAO.getCheckSignature())) {
            return ResultBuilder.failure("90000013");
        }
        PatientUser patientUserByOpenid = patientUserService.getPatientUserByOpenid(wechatPatientLoginAO.getOpenid());
        if (patientUserByOpenid != null) {
            Session session = SessionTool.buildLonginSession(jwtUtil, 2, patientUserByOpenid.getId());
            sessionService.insert(session);
            LoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId());
            return ResultBuilder.success(loginVO);
        }

        final WxMaService wxService = WxMaConfiguration.getMaService();
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(wechatPatientLoginAO.getSessionKey(), wechatPatientLoginAO.getEncryptedData(), wechatPatientLoginAO.getIv());
        if (phoneNoInfo == null || StringUtils.isBlank(phoneNoInfo.getPhoneNumber())) {
            return ResultBuilder.failure("90000013");
        }
        PatientUser patientUser = patientUserService.getPatientUserByPhone(phoneNoInfo.getPhoneNumber());
        Long patientUserId = null;
        if (patientUser == null) {
            PatientUser patientUserWechatRegister = AppCommonTool.buildPatientUserWechatRegister(wechatPatientLoginAO.getOpenid(), phoneNoInfo.getPhoneNumber());
            patientUserId = patientUserService.insert(patientUserWechatRegister);
        } else {
            PatientUser patientUserWechatRegister = AppCommonTool.buildPatientUserWechatRegister(patientUser, wechatPatientLoginAO.getOpenid());
            patientUserService.update(patientUserWechatRegister);
            patientUserId = patientUserWechatRegister.getId();
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 2, patientUserId);
        sessionService.insert(session);
        LoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId());
        return ResultBuilder.success(loginVO);
    }


    @ApiOperation("获取抖音openId")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "获取抖音openId")
    @PostMapping("getOpenIdDouYin")
    public ResultDTO<Object> getOpenIdDouyin(@RequestBody PatientWechatSessionAO patientWechatSessionAO){
        if (StringUtils.isEmpty(patientWechatSessionAO.getCode()) || StringUtils.isEmpty(patientWechatSessionAO.getAnonymousCode())) {
            return ResultBuilder.failure("1", "参数有误");
        }
        JSONObject result = patientUserService.getOpenIdDouYin(patientWechatSessionAO.getCode(), patientWechatSessionAO.getAnonymousCode());
        if(result == null){
            return ResultBuilder.failure("1", "获取openId失败");
        }
        return ResultBuilder.success(result);
    }

    @ApiOperation("抖音小程序登录")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "抖音小程序登录")
    @PostMapping("patientDouYinLogin")
    public ResultDTO<Object> patientDouyinLogin(@RequestBody PatientWechatSessionAO patientWechatSessionAO) throws Exception{
        if (StringUtils.isEmpty(patientWechatSessionAO.getCode()) || StringUtils.isEmpty(patientWechatSessionAO.getAnonymousCode())) {
            return ResultBuilder.failure("1", "参数有误");
        }
        JSONObject result = patientUserService.getOpenIdDouYin(patientWechatSessionAO.getCode(), patientWechatSessionAO.getAnonymousCode());
        if(result == null){
            return ResultBuilder.failure("1", "获取openId失败");
        }
        // 根据openid查询患者信息
        Long patientUserId = null;
        PatientUser patientUser = patientUserService.getPatientUserByOpenidDy(result.get("openid").toString());
        if(patientUser == null){
            PatientUser patientUserWechatRegister = AppCommonTool.buildPatientUserDouYinRegister(result.get("openid").toString(), result.get("anonymous_openid").toString());
            patientUserId = patientUserService.insert(patientUserWechatRegister);
        } else {
            patientUserId = patientUser.getId();
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 2, patientUserId);
        sessionService.insert(session);
        LoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId());
        return ResultBuilder.success(loginVO);
    }


    @ApiOperation("微信小程序患者端手机验证码登录")
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.UPDATE, desc = "微信小程序患者端手机验证码登录")
    @PostMapping("patientWechat2PhoneLogin")
    public ResultDTO<LoginVO> patientWechat2PhoneLogin(@RequestBody PatientWechat2PhoneLoginAO patientWechat2PhoneLoginAO) throws Exception {
        AppCommonTool.checkPatientWechat2PhoneLogin(patientWechat2PhoneLoginAO);
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(patientWechat2PhoneLoginAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0 || !patientWechat2PhoneLoginAO.getSmsCode().equals(smsCaptcha.getCode())) {
            return ResultBuilder.failure("10010027");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010017");
        }
        Long patientUserId = null;
        PatientUser patientUserByPhone = patientUserService.getPatientUserByPhone(patientWechat2PhoneLoginAO.getPhone());
        if (patientUserByPhone == null) {
            PatientUser patientUserWechatRegister = AppCommonTool.buildPatientUserWechatRegister(patientWechat2PhoneLoginAO.getPhone());
            patientUserId = patientUserService.insert(patientUserWechatRegister);
        } else {
            patientUserId = patientUserByPhone.getId();
        }
        Session session = SessionTool.buildLonginSession(jwtUtil, 2, patientUserId);
        sessionService.insert(session);
        LoginVO loginVO = AppCommonTool.buildLoginVO(session.getToken(), session.getUserId());
        return ResultBuilder.success(loginVO);
    }

    @ApiOperation("获取用户登录概括信息")
    @PostMapping(value = {"/getUserProfile"})
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "获取用户登录概括信息")
    public Object getUserProfile() throws BizException {
        Integer userType = ReqComTool.getUserType();
        UserProfileVO userProfileVO = new UserProfileVO();
        userProfileVO.setUserType(userType);
        Long userId = ReqComTool.getUserId();
        userProfileVO.setUserId(userId);
        if (userType == 1) {
            PatientUser patientUser = patientUserService.findById(userId);
            userProfileVO.setOpenid(patientUser.getOpenid());

        }
        return ResultBuilder.success(userProfileVO);
    }

    @ApiOperation("用户退出登录")
    @PostMapping(value = {"/loginOut"})
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "用户退出登录")
    public Object loginOut() throws BizException {
        Long sessionId = ReqComTool.getSessionId();
        sessionService.stopUseSession(sessionId);
        return ResultBuilder.success(null);
    }

    @ApiOperation("注销患者账户")
    @PostMapping(value = {"/closePatientAccount"})
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "注销患者账户")
    public Object closePatientAccount(@RequestBody ClosePatientAccountAO closePatientAccountAO) throws BizException {
        SmsCaptcha smsCaptcha = smsCaptchaService.findById(closePatientAccountAO.getSmsPkId());
        if (smsCaptcha == null || smsCaptcha.getBizStatus() == 0 || !closePatientAccountAO.getSmsCode().equals(smsCaptcha.getCode())) {
            return ResultBuilder.failure("10010027");
        }
        if (DateUtil.currDate().getTime() - DateUtil.getMinuteAgoOrAfter(smsCaptcha.getUpdateTime(), customConf.getSmsCaptchaTime()).getTime() > 0) {
            return ResultBuilder.failure("10010017");
        }
        Long sessionId = ReqComTool.getSessionId();
        sessionService.stopUseSession(sessionId);
        Long userId = ReqComTool.getUserId();
        patientUserService.delById(userId);
        return ResultBuilder.success(null);
    }


    @ApiOperation("用户APP版本检查")
    @PostMapping(value = {"/checkVersion"})
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "用户APP版本检查")
    public ResultDTO<AppVersionVO> checkVersion(@Valid @RequestBody VersionCheckAO checkAO) {
        AppVersionDTO appVersionDTO = CommonTool.copyProperties(checkAO, AppVersionDTO.class);
        appVersionDTO.setPublish(1);
        List<AppVersion> appVersions = appVersionService.list(appVersionDTO);
        AppVersionVO vo = CollectionUtils.isEmpty(appVersions)
                ? null : CommonTool.copyProperties(appVersions.get(0), AppVersionVO.class);
        return ResultBuilder.success(vo);
    }

    @ApiOperation("App下载二维码")
    @PostMapping(value = {"/downloadApp"})
    @Log(source = LogSourceEnum.APP, type = LogTypeEnum.SELECT, desc = "App下载二维码")
    public ResultDTO<String> downloadApp(@Valid @RequestBody DownloadAppAO downloadAppAO) {
        return ResultBuilder.success(downloadAppAO == null || downloadAppAO.getType() == 0 ? downloadAppQrDoctor : downloadAppQrPatient);
    }

    @GetMapping("health")
    public ResultDTO health(){
        return ResultBuilder.success();
    }

}
